<template>
  <div class="auto-login-container">
    <div class="main-content">
      <!-- 左侧主要功能区 -->
      <div class="left-panel">
        <n-card title="自动登录工具" class="login-card">
          <n-space vertical size="large">
            <!-- 数据库连接状态 -->
            <div class="section">
              <n-text class="section-title">数据库连接状态</n-text>
              <n-space>
                <n-button
                  size="small"
                  :type="
                    dbStatus === 'connected'
                      ? 'success'
                      : dbStatus === 'disconnected'
                      ? 'error'
                      : 'default'
                  "
                  :loading="isTestingConnection"
                  @click="testConnection"
                >
                  <template #icon>
                    <n-icon>
                      <DatabaseIcon />
                    </n-icon>
                  </template>
                  {{ dbStatusText }}
                </n-button>
                <n-text depth="3" style="font-size: 12px">
                  {{ dbStatus === 'connected' ? '从Oracle数据库获取用户' : '从本地文件获取用户' }}
                </n-text>
              </n-space>
            </div>

            <!-- 环境选择 -->
            <div class="section">
              <n-text class="section-title">选择环境</n-text>
              <n-radio-group v-model:value="selectedEnvironment" size="large">
                <n-space>
                  <n-radio-button
                    v-for="env in environments"
                    :key="env.value"
                    :value="env.value"
                    :label="env.label"
                    class="env-button"
                  />
                </n-space>
              </n-radio-group>
            </div>

            <!-- 用户选择 -->
            <div class="section">
              <n-text class="section-title">选择用户</n-text>
              <n-select
                v-model:value="selectedUserId"
                :options="userOptions"
                filterable
                clearable
                placeholder="请选择用户"
                size="large"
                :loading="isLoadingUsers"
                class="user-select"
              />
            </div>

            <!-- 浏览器选择 -->
            <div class="form-item">
              <label>选择浏览器:</label>
              <n-select
                size="large"
                class="user-select"
                v-model:value="selectedBrowser"
                :options="browserOptions"
                placeholder="请选择浏览器"
              />
            </div>

            <!-- 操作按钮 -->
            <div class="section">
              <n-space>
                <n-button
                  type="primary"
                  size="large"
                  :disabled="!canLogin"
                  :loading="isLoggingIn"
                  @click="handleLogin"
                >
                  <template #icon>
                    <n-icon>
                      <LoginIcon />
                    </n-icon>
                  </template>
                  启动登录
                </n-button>

                <n-button size="large" @click="refreshUsers" :loading="isLoadingUsers">
                  <template #icon>
                    <n-icon>
                      <RefreshIcon />
                    </n-icon>
                  </template>
                  刷新用户
                </n-button>
              </n-space>
            </div>

            <!-- 当前配置显示 -->
            <div class="section" v-if="currentConfig">
              <n-text class="section-title">当前配置</n-text>
              <n-card size="small" class="config-display">
                <n-descriptions :column="1" size="small">
                  <n-descriptions-item label="环境"
                    >{{ currentConfig.environment }}
                  </n-descriptions-item>
                  <n-descriptions-item label="用户" v-if="currentConfig.userName">
                    {{ currentConfig.userName }} ({{ currentConfig.userId }})
                  </n-descriptions-item>
                  <n-descriptions-item label="组织" v-if="currentConfig.orgName">
                    {{ currentConfig.orgName }}
                  </n-descriptions-item>
                  <n-descriptions-item label="Token" v-if="currentConfig.token">
                    {{ currentConfig.token }}
                  </n-descriptions-item>
                  <n-descriptions-item label="登录URL" v-if="currentConfig.loginUrl">
                    <n-ellipsis style="max-width: 400px">
                      {{ currentConfig.loginUrl }}
                    </n-ellipsis>
                    <n-button
                      size="tiny"
                      type="primary"
                      text
                      style="margin-left: 8px"
                      @click="copyUrl"
                    >
                      复制
                    </n-button>
                  </n-descriptions-item>
                </n-descriptions>
              </n-card>
            </div>
          </n-space>
        </n-card>
      </div>

      <!-- 右侧排行榜 -->
      <div class="right-panel">
        <n-card title="登录排行榜" class="ranking-card">
          <template #header-extra>
            <n-space>
              <n-select
                v-model:value="rankingFilter"
                :options="rankingFilterOptions"
                size="small"
                style="width: 120px"
              />
              <n-button size="small" @click="loadRanking" :loading="isLoadingRanking">
                <template #icon>
                  <n-icon>
                    <RefreshIcon />
                  </n-icon>
                </template>
              </n-button>
            </n-space>
          </template>

          <div class="ranking-content">
            <n-data-table
              :columns="rankingColumns"
              :data="filteredRankingData"
              :pagination="false"
              size="small"
              :max-height="400"
              :row-props="rankingRowProps"
              class="ranking-table"
            />
          </div>
        </n-card>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, onMounted, watch, h } from 'vue';
  import { useMessage } from 'naive-ui';
  import {
    LogIn as LoginIcon,
    Refresh as RefreshIcon,
    Server as DatabaseIcon,
    Trophy as TrophyIcon,
  } from '@vicons/ionicons5';
  import { invoke } from '@tauri-apps/api/core';
  import type { DataTableColumns } from 'naive-ui';

  // 类型定义
  interface Environment {
    value: string;
    label: string;
    description?: string;
  }

  // 添加浏览器相关类型和数据
  interface BrowserInfo {
    name: string;
    value: string;
    available: boolean;
  }

  interface UserInfo {
    userid: string;
    username: string;
    pinyin: string;
    firstpy: string;
    orgname: string;
  }

  interface UserOption {
    label: string;
    value: string;
    orgName?: string;
  }

  interface UserGroup {
    type: 'group';
    label: string;
    key: string;
    children: UserOption[];
  }

  interface LoginConfig {
    environment: string;
    userName?: string;
    userId?: string;
    orgName?: string;
    token?: string;
    loginUrl?: string;
  }

  interface RankingItem {
    rank: number;
    user_id: string;
    username: string;
    environment: string;
    click_count: number;
    last_used: string;
    org_name?: string;
  }

  const selectedBrowser = ref('default');
  const availableBrowsers = ref<BrowserInfo[]>([]);

  // 计算可用的浏览器选项
  const browserOptions = computed(() => {
    return availableBrowsers.value
      .filter((browser) => browser.available)
      .map((browser) => ({
        label: browser.name,
        value: browser.value,
      }));
  });

  // 检测可用浏览器
  const detectBrowsers = async () => {
    try {
      const browsers = await invoke<BrowserInfo[]>('detect_available_browsers');
      console.log(11111);
      console.log(browsers);
      availableBrowsers.value = browsers;
    } catch (error) {
      console.error('检测浏览器失败:', error);
      // 如果检测失败，至少提供默认选项
      availableBrowsers.value = [
        {
          name: '系统默认浏览器',
          value: 'default',
          available: true,
        },
      ];
    }
  };

  // 环境配置
  const environments: Environment[] = [
    {
      value: '55',
      label: '生产环境 (55)',
      description: '生产环境服务器',
    },
    {
      value: '54',
      label: '测试环境 (54)',
      description: '测试环境服务器',
    },
    {
      value: 'localhost',
      label: '本地环境',
      description: '本地开发环境',
    },
  ];

  // 排行榜筛选选项
  const rankingFilterOptions = [
    { label: '全部', value: 'all' },
    { label: '生产环境', value: '55' },
    { label: '测试环境', value: '54' },
    { label: '本地环境', value: 'localhost' },
  ];

  // 响应式数据
  const message = useMessage();
  const selectedEnvironment = ref('55');
  const selectedUserId = ref<string | null>(null);
  const userOptions = ref<(UserOption | UserGroup)[]>([]);
  const isLoadingUsers = ref(false);
  const isLoggingIn = ref(false);
  const isTestingConnection = ref(false);
  const dbStatus = ref<'unknown' | 'connected' | 'disconnected'>('unknown');
  const userList = ref<UserInfo[]>([]);

  // 排行榜相关数据
  const rankingData = ref<RankingItem[]>([]);
  const isLoadingRanking = ref(false);
  const rankingFilter = ref('all');

  // 排行榜表格列定义
  const rankingColumns: DataTableColumns<RankingItem> = [
    {
      title: '排名',
      key: 'rank',
      width: 60,
      render: (row) => {
        const iconColor = row.rank <= 3 ? ['#FFD700', '#C0C0C0', '#CD7F32'][row.rank - 1] : '#666';
        return h('div', { style: 'display: flex; align-items: center; gap: 4px;' }, [
          h(TrophyIcon, { style: `color: ${iconColor}; font-size: 16px;` }),
          h('span', { style: 'font-weight: bold;' }, row.rank),
        ]);
      },
    },
    {
      title: '用户',
      key: 'username',
      ellipsis: {
        tooltip: true,
      },
      render: (row) =>
        h('div', [
          h('div', { style: 'font-weight: 500;' }, row.username),
          h('div', { style: 'font-size: 12px; color: #666;' }, row.user_id), // 改为 user_id
        ]),
    },
    {
      title: '环境',
      key: 'environment',
      width: 80,
      render: (row) => {
        const envMap: Record<string, string> = {
          '55': '生产',
          '54': '测试',
          localhost: '本地',
        };
        return envMap[row.environment] || row.environment;
      },
    },
    {
      title: '次数',
      key: 'click_count',
      width: 60,
      render: (row) => h('span', { style: 'font-weight: 500; color: #1890ff;' }, row.click_count),
    },
    {
      title: '最近登录',
      key: 'last_used', // 改为 last_used
      width: 100,
      render: (row) => {
        const date = new Date(row.last_used); // 改为 last_used
        const now = new Date();
        const diffMs = now.getTime() - date.getTime();
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

        if (diffDays === 0) {
          return h('span', { style: 'color: #52c41a;' }, '今天');
        } else if (diffDays === 1) {
          return h('span', { style: 'color: #faad14;' }, '昨天');
        } else if (diffDays < 7) {
          return h('span', { style: 'color: #1890ff;' }, `${diffDays}天前`);
        } else {
          return h('span', { style: 'color: #666;' }, date.toLocaleDateString());
        }
      },
    },
  ];

  // 计算属性
  const currentEnvironment = computed(() =>
    environments.find((env) => env.value === selectedEnvironment.value)
  );

  const selectedUser = computed(() => {
    if (!selectedUserId.value) return null;
    return userList.value.find((user) => user.userid === selectedUserId.value) || null;
  });

  const canLogin = computed(
    () => selectedEnvironment.value && selectedUserId.value && !isLoggingIn.value
  );

  const dbStatusText = computed(() => {
    switch (dbStatus.value) {
      case 'connected':
        return '数据库已连接';
      case 'disconnected':
        return '数据库未连接';
      default:
        return '测试连接';
    }
  });

  // 将计算属性改为响应式数据
  const currentConfig = ref<LoginConfig | null>(null);

  // 添加一个计算属性来监听环境和用户变化
  const updateCurrentConfig = () => {
    if (!currentEnvironment.value || !selectedUser.value) {
      currentConfig.value = null;
      return;
    }

    currentConfig.value = {
      environment: currentEnvironment.value.label,
      userName: selectedUser.value.username,
      userId: selectedUser.value.userid,
      orgName: selectedUser.value.orgname,
      token: currentConfig.value?.token || undefined,
      loginUrl: currentConfig.value?.loginUrl || undefined,
    };
  };

  // 监听环境和用户变化
  watch([selectedEnvironment, selectedUserId], updateCurrentConfig, { immediate: true });

  // 筛选后的排行榜数据
  const filteredRankingData = computed(() => {
    if (rankingFilter.value === 'all') {
      return rankingData.value;
    }
    return rankingData.value.filter((item) => item.environment === rankingFilter.value);
  });

  // 排行榜行属性
  const rankingRowProps = (row: RankingItem) => {
    return {
      style: 'cursor: pointer;',
      onClick: () => handleRankingRowClick(row),
    };
  };

  // 测试数据库连接
  const testConnection = async (): Promise<void> => {
    if (isTestingConnection.value) return;

    isTestingConnection.value = true;
    try {
      const settings = (await invoke('get_user_settings')) as any;
      // 修改这一行：从 settings.auto_login.database 改为 settings.database
      await invoke('test_database_connection', { config: settings.database });
      dbStatus.value = 'connected';
      message.success('数据库连接测试成功');
    } catch (error) {
      dbStatus.value = 'disconnected';
      message.warning(`数据库连接失败: ${error}`);
    } finally {
      isTestingConnection.value = false;
    }
  };

  // 加载用户列表
  const loadUsers = async (): Promise<void> => {
    if (isLoadingUsers.value) return;

    isLoadingUsers.value = true;
    try {
      const users = (await invoke('get_auto_login_users', {
        environment: selectedEnvironment.value,
      })) as UserInfo[];

      userList.value = users;

      // 按组织分组用户
      const groupedUsers = new Map<string, UserOption[]>();

      users.forEach((user) => {
        const orgName = user.orgname || '未分组';
        const userOption: UserOption = {
          label: `${user.username} (${user.userid})`,
          value: user.userid,
          orgName: orgName,
        };

        if (!groupedUsers.has(orgName)) {
          groupedUsers.set(orgName, []);
        }
        groupedUsers.get(orgName)!.push(userOption);
      });

      // 转换为选择器格式
      userOptions.value = Array.from(groupedUsers.entries()).map(([orgName, users]) => ({
        type: 'group' as const,
        label: orgName,
        key: orgName,
        children: users,
      }));

      message.success(`成功加载 ${users.length} 个用户`);
    } catch (error) {
      console.error('加载用户失败:', error);
      message.error(`加载用户失败: ${error}`);
      userOptions.value = [];
      userList.value = [];
    } finally {
      isLoadingUsers.value = false;
    }
  };

  // 加载排行榜数据
  const loadRanking = async (): Promise<void> => {
    if (isLoadingRanking.value) return;

    isLoadingRanking.value = true;
    try {
      const ranking = (await invoke('get_login_ranking', {
        limit: 50,
        environment: rankingFilter.value === 'all' ? null : rankingFilter.value,
      })) as RankingItem[];

      rankingData.value = ranking;
    } catch (error) {
      console.error('加载排行榜失败:', error);
      message.error(`加载排行榜失败: ${error}`);
      rankingData.value = [];
    } finally {
      isLoadingRanking.value = false;
    }
  };

  // 刷新用户列表
  const refreshUsers = async (): Promise<void> => {
    selectedUserId.value = null;
    await loadUsers();
  };

  // 处理排行榜行点击
  const handleRankingRowClick = async (row: RankingItem): Promise<void> => {
    try {
      // 设置环境和用户
      selectedEnvironment.value = row.environment;
      selectedUserId.value = row.user_id; // 改为 user_id

      // 等待环境切换完成后重新加载用户
      await loadUsers();

      // 自动登录
      await handleLogin();

      message.success(`快速登录: ${row.username} (${row.environment})`);
    } catch (error) {
      console.error('快速登录失败:', error);
      message.error(`快速登录失败: ${error}`);
    }
  };

  // 处理登录
  const handleLogin = async (): Promise<void> => {
    if (!canLogin.value || !currentEnvironment.value || !selectedUserId.value) {
      message.warning('请选择环境和用户');
      return;
    }

    isLoggingIn.value = true;
    try {
      // 记录点击
      await invoke('record_login_click', {
        userId: selectedUserId.value,
        environment: selectedEnvironment.value,
      });

      // 构建登录URL
      const loginUrl = (await invoke('build_auto_login_url', {
        environment: selectedEnvironment.value,
        userid: selectedUserId.value,
      })) as string;

      console.log('正在打开URL:', loginUrl);

      // 根据选择的浏览器打开URL
      if (selectedBrowser.value === 'default') {
        await invoke('open_url', { url: loginUrl });
      } else {
        await invoke('open_url_with_browser', {
          url: loginUrl,
          browser: selectedBrowser.value,
        });
      }

      // 更新当前配置显示
      if (currentConfig.value) {
        // 获取用户设置中的key
        const settings = (await invoke('get_user_settings')) as any;
        const key = settings.auto_login?.environments?.key || '';
        const token = (await invoke('generate_login_token', { key })) as string;
        // 直接更新响应式数据
        currentConfig.value.token = token;
        currentConfig.value.loginUrl = loginUrl;
      }

      // 刷新排行榜
      await loadRanking();
    } catch (error) {
      console.error('打开URL失败:', error);
      message.error(`打开登录页面失败: ${error}`);
    } finally {
      isLoggingIn.value = false;
    }
  };

  // 监听环境变化
  watch(selectedEnvironment, () => {
    // 移除自动清空用户选择的逻辑
    // selectedUserId.value = null;
  });

  // 监听排行榜筛选变化
  watch(rankingFilter, () => {
    loadRanking();
  });

  // 组件挂载
  onMounted(async () => {
    // 初始化数据库
    try {
      await invoke('init_login_stats_db');
      await detectBrowsers();
    } catch (error) {
      console.error('初始化统计数据库失败:', error);
    }

    await testConnection();
    await loadUsers();
    await loadRanking();
  });
  // 复制URL到剪贴板
  const copyUrl = async (): Promise<void> => {
    if (currentConfig.value?.loginUrl) {
      try {
        await navigator.clipboard.writeText(currentConfig.value.loginUrl);
        message.success('URL已复制到剪贴板');
      } catch (error) {
        console.error('复制失败:', error);
        message.error('复制失败');
      }
    }
  };
</script>

<style scoped>
  .auto-login-container {
    padding: 24px;
    /* 移除固定高度 */
    /* height: 100vh; */
    /* overflow: hidden; */
    box-sizing: border-box;
  }

  .main-content {
    display: flex;
    gap: 24px;
    /* 移除固定高度和overflow限制 */
    /* height: calc(100% - 0px); */
    /* overflow: hidden; */
    min-height: 0; /* 确保flex容器可以正常工作 */
  }

  .left-panel {
    flex: 1;
    min-width: 500px;
    /* 移除固定高度和滚动条 */
    /* overflow-y: auto; */
    /* height: 100%; */
  }

  .right-panel {
    width: 40%;
    /* 移除固定高度和滚动条 */
    /* overflow-y: auto; */
    /* height: 100%; */
  }

  .ranking-card {
    /* 让排行榜卡片自适应内容高度 */
    display: flex;
    flex-direction: column;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    /* 移除固定高度，让它自适应内容 */
  }

  .section {
    padding: 16px 0;
  }

  .section-title {
    display: block;
    font-weight: 600;
    margin-bottom: 12px;
    color: #333;
  }

  .env-button {
    min-width: 140px;
  }

  .user-select {
    width: 100%;
    max-width: 400px;
  }

  .config-display {
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
  }

  /* 排行榜表格样式 */
  :deep(.n-data-table-tbody .n-data-table-tr:hover) {
    background-color: #f0f9ff;
    transform: translateY(-1px);
    transition: all 0.2s ease;
  }

  :deep(.n-data-table-tbody .n-data-table-tr) {
    transition: all 0.2s ease;
  }

  @media (max-width: 1200px) {
    .main-content {
      flex-direction: column;
    }

    .right-panel {
      width: 100%;
      height: 400px;
    }

    .ranking-card {
      height: 400px;
    }
  }

  @media (max-width: 768px) {
    .auto-login-container {
      padding: 16px;
    }

    .env-button {
      min-width: 100px;
    }

    .user-select {
      max-width: 100%;
    }

    .left-panel {
      min-width: auto;
    }
  }
</style>
